﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NutriLeaf.Web.Core.Sleep
{
    public class Sleep:ISleep
    {
        public void InsertUserSleep(int userId, TimeSpan duration, DateTime clientDateTime, ref Model.NutriLeafDBEntities context)
        {
            Model.Sleep sleep = new Model.Sleep();
            sleep.Duration = duration;
            sleep.UserID = userId;
            sleep.DateTimeStamp = clientDateTime;
            context.Sleeps.AddObject(sleep);
            context.SaveChanges();
        }

        public void InsertUserSleep(Model.User user, TimeSpan duration, DateTime clientDatetime, ref Model.NutriLeafDBEntities context)
        {
            Model.Sleep sleep = new Model.Sleep();
            sleep.Duration = duration;
            sleep.User = user;
            sleep.DateTimeStamp = clientDatetime;
            context.Sleeps.AddObject(sleep);
            context.SaveChanges();
        }

        public void InsertUserSleep(Model.Sleep sleep, ref Model.NutriLeafDBEntities context)
        {
            context.Sleeps.AddObject(sleep);
            context.SaveChanges();
        }

        public TimeSpan HoursUsersSleptInDay(int userId, DateTime clientDateTime, ref Model.NutriLeafDBEntities context)
        {
            return context.Sleeps.Where(p => p.UserID == userId && p.DateTimeStamp == clientDateTime).First().Duration;
        }

        public void RemoveUserSleep(int sleepId, ref Model.NutriLeafDBEntities context)
        {
            context.DeleteObject(context.Sleeps.Where(p => p.SleepID == sleepId).First());
            context.SaveChanges();
        }

        public void RemoveUserSleep(Model.Sleep sleep, ref Model.NutriLeafDBEntities context)
        {
            context.DeleteObject(context.Sleeps.Where(p => p.SleepID == sleep.SleepID).First());
            context.SaveChanges();
        }

        public List<Model.Sleep> GetSleepsInDay(int userId, DateTime clientDateTime, ref Model.NutriLeafDBEntities context)
        {
            return context.Sleeps.Where(p => p.UserID == userId && p.DateTimeStamp == clientDateTime).ToList();
        }

        public List<Model.Sleep> GetSleepList(int userId, DateTime clientDateTimeStart, DateTime clientDateTimeEnd, ref Model.NutriLeafDBEntities context)
        {
            return context.Sleeps.Where(p => p.UserID == userId && p.DateTimeStamp >= clientDateTimeStart && p.DateTimeStamp < clientDateTimeEnd).ToList();
        }
    }
}